<template>
  <div>
    <div class="avatar-box">
      <el-avatar shape="square" :size="100" :fit="'fill'" :src="avatarUrl" @click="openUpload" />
    </div>

    <el-dialog v-model="open" draggable :title="'上传头像'">
      <el-upload
        :class="{ hideUploadBtn: hideUploadBtn }"
        :http-request="uploadFile"
        list-type="picture-card"
        :before-upload="beforeUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :multiple="false"
        v-model:file-list="fileList"
        :limit="1"
        accept="image/*"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
    </el-dialog>
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadFile, UploadRequestOptions, UploadUserFile } from "element-plus";
import FileApi, { FileModel } from "@/api/file";
import { useUserStore } from "@/store";
import { FileEnum } from "@/enums/FileEnum";

const userStore = useUserStore();

const formData = ref<FileModel>({
  mainId: userStore.userInfo.id,
  module: FileEnum.AVATAR,
});

const avatarUrl = ref(userStore.userInfo.avatarUrl);

const hideUploadBtn = ref(false);
const fileList = ref<UploadUserFile[]>([]);
watch(
  () => fileList.value.length,
  () => {
    if (fileList.value.length === 0) {
      hideUploadBtn.value = false;
    } else {
      hideUploadBtn.value = true;
    }
  }
);

const open = ref(false);
const openUpload = () => {
  open.value = true;
  if (fileList.value.length === 0) {
    const fileImage = ref<UploadUserFile>({
      name: "",
      url: avatarUrl.value,
    });
    fileList.value.push(fileImage.value);
  }
};

/** 上传文件 */
const uploadFile = async (options: UploadRequestOptions) => {
  formData.value.file = options.file;
  const { success, message } = await FileApi.UploadSingleFile(formData.value);
  ElMessage({
    message: message,
    type: "success",
  });
  if (success) {
    const reader = new FileReader();
    reader.readAsDataURL(options.file); // 读取文件为Base64
    reader.onloadend = function (e) {
      avatarUrl.value = e.target.result as string;
      userStore.userInfo.avatarUrl = avatarUrl.value;
    };
  }
};

/** 上传文件前 */
const beforeUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!;
  dialogVisible.value = true;
};

const handleRemove = (file: UploadFile) => {
  fileList.value = fileList.value.filter((x) => x.uid != file.uid);
};
</script>

<style scoped>
.avatar-box {
  text-align: center;
}
.el-avatar:hover {
  cursor: pointer;
}
</style>

<style>
.hideUploadBtn .el-upload--picture-card {
  display: none;
}
</style>
